<template>
  <div class="create-role-page">
    <div class="container">
      <div class="page-header">
        <h1 class="page-title">创建AI角色</h1>
        <p class="page-subtitle">设计你的专属AI伙伴</p>
      </div>
      
      <div class="form-container">
        <form @submit.prevent="submitRole" class="role-form">
          <div class="form-section">
            <h3 class="section-title">基本信息</h3>
            
            <div class="form-group">
              <label for="name" class="form-label">角色名称 *</label>
              <input
                id="name"
                v-model="form.name"
                type="text"
                class="form-input"
                placeholder="给你的AI角色起个名字"
                required
              />
            </div>
            
            <div class="form-group">
              <label for="description" class="form-label">角色描述</label>
              <textarea
                id="description"
                v-model="form.description"
                class="form-textarea"
                placeholder="描述这个角色的性格、特点等"
                rows="4"
              ></textarea>
            </div>
            
            <div class="form-group">
              <label for="avatar" class="form-label">角色头像</label>
              <div class="avatar-upload">
                <div class="avatar-preview" @click="triggerFileInput">
                  <img v-if="form.avatarUrl" :src="form.avatarUrl" :alt="form.name" />
                  <div v-else class="avatar-placeholder">
                    <span v-if="loading" class="upload-icon">⏳</span>
                    <span v-else class="upload-icon">📷</span>
                    <span class="upload-text">{{ loading ? '上传中...' : '点击上传' }}</span>
                  </div>
                </div>
                <input
                  ref="fileInput"
                  id="avatar"
                  type="file"
                  accept="image/*"
                  @change="handleAvatarUpload"
                  class="avatar-input"
                  :disabled="loading"
                />
              </div>
            </div>
          </div>
          
          <div class="form-section">
            <h3 class="section-title">角色设定</h3>
            
            <div class="form-group">
              <label for="category" class="form-label">角色类别</label>
              <select id="category" v-model="form.category" class="form-input">
                <option value="">请选择类别</option>
                <option value="assistant">助手</option>
                <option value="entertainment">娱乐</option>
                <option value="education">教育</option>
                <option value="business">商务</option>
                <option value="creative">创作</option>
                <option value="life">生活</option>
              </select>
            </div>
            
            <div class="form-group">
              <label for="personality" class="form-label">性格特点</label>
              <textarea
                id="personality"
                v-model="form.personality"
                class="form-textarea"
                placeholder="描述角色的性格特点，如：温柔、活泼、聪明等"
                rows="3"
              ></textarea>
            </div>
            
            <div class="form-group">
              <label for="background" class="form-label">背景故事</label>
              <textarea
                id="background"
                v-model="form.background"
                class="form-textarea"
                placeholder="角色的背景故事，帮助AI更好地理解角色"
                rows="4"
              ></textarea>
            </div>
            
            <div class="form-group">
              <label for="speakingStyle" class="form-label">说话风格</label>
              <textarea
                id="speakingStyle"
                v-model="form.speakingStyle"
                class="form-textarea"
                placeholder="描述角色的说话风格，如：正式、随意、可爱等"
                rows="3"
              ></textarea>
            </div>
            
            <div class="form-row">
              <div class="form-group">
                <label for="promptTemplate" class="form-label">提示词模板</label>
                <textarea
                  id="promptTemplate"
                  v-model="form.promptTemplate"
                  class="form-textarea"
                  placeholder="定义角色的核心提示词模板，用于指导AI的行为"
                  rows="4"
                ></textarea>
              </div>
              
              <div class="form-group">
                <label for="openingLine" class="form-label">开场白</label>
                <textarea
                  id="openingLine"
                  v-model="form.openingLine"
                  class="form-textarea"
                  placeholder="角色与用户初次见面时的开场白"
                  rows="4"
                ></textarea>
              </div>
            </div>
          </div>
          
          <div class="form-section">
            <h3 class="section-title">高级设置</h3>
            
            <div class="form-group">
              <label for="defaultVoice" class="form-label">默认音色</label>
              <div class="voice-selector-container">
                <div class="voice-selector" @click="showVoiceSelector = !showVoiceSelector">
                  <span v-if="selectedVoice">{{ getVoiceDisplayName(selectedVoice) }}</span>
                  <span v-else class="placeholder">选择默认音色</span>
                  <span class="dropdown-arrow">▼</span>
                </div>
                
                <div v-if="showVoiceSelector" class="voice-dropdown">
                  <div class="voice-dropdown-header">
                    <h4>选择音色</h4>
                    <button @click="showVoiceSelector = false" class="close-btn">×</button>
                  </div>
                  <div class="voice-list">
                    <div v-if="voiceList.length === 0" class="empty-voice-list">
                      <p>暂无可用音色</p>
                    </div>
                    <div v-for="voice in voiceList" :key="voice.voice_type" 
                         class="voice-item" 
                         :class="{ selected: selectedVoice === voice.voice_type }"
                         @click="selectVoice(voice.voice_type)">
                      <div class="voice-info">
                        <span class="voice-name">{{ voice.voice_name || voice.voice_type }}</span>
                        <span class="voice-description">{{ voice.category || voice.voice_type }}</span>
                      </div>
                      <div class="voice-preview">
                        <button @click.stop="previewVoice(voice.voice_type)" class="preview-btn">试听</button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            
            <div class="form-row">
              <div class="form-group">
                <label for="tags" class="form-label">标签</label>
                <input
                  id="tags"
                  v-model="form.tags"
                  type="text"
                  class="form-input"
                  placeholder="用逗号分隔，如：温柔,学生,二次元"
                />
              </div>
              
              <div class="form-group">
                <label for="privacy" class="form-label">可见性</label>
                <select id="privacy" v-model="form.privacy" class="form-select">
                  <option value="PUBLIC">公开</option>
                  <option value="PRIVATE">私有</option>
                </select>
              </div>
            </div>
            
            <div class="form-group">
              <label class="form-label">
                <input
                  v-model="form.allowVoice"
                  type="checkbox"
                  class="form-checkbox"
                />
                启用语音对话
              </label>
            </div>
          </div>
          
          <div v-if="error" class="error-message">
            {{ error }}
          </div>
          
          <div class="form-actions">
            <button type="button" @click="goBack" class="btn btn-secondary">取消</button>
            <button type="submit" class="btn btn-primary" :disabled="loading">
              <span v-if="loading" class="loading-spinner"></span>
              {{ loading ? '创建中...' : '创建角色' }}
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const loading = ref(false)
const error = ref('')
const fileInput = ref(null)
const showVoiceSelector = ref(false)
const voiceList = ref([])
const selectedVoice = ref('')

const form = ref({
  name: '',
  description: '',
  avatarUrl: '',
  personality: '',
  background: '',
  speakingStyle: '',
  promptTemplate: '',
  openingLine: '',
  tags: '',
  privacy: 'PUBLIC',
  allowVoice: true,
  category: '',
  defaultVoiceType: ''
})

// 触发文件选择
const triggerFileInput = () => {
  if (fileInput.value) {
    fileInput.value.click()
  }
}

const handleAvatarUpload = async (event) => {
  const file = event.target.files[0]
  if (!file) return
  
  if (file.size > 5 * 1024 * 1024) {
    error.value = '头像文件大小不能超过5MB'
    return
  }
  
  // 验证文件类型
  if (!file.type.startsWith('image/')) {
    error.value = '只支持图片文件'
    return
  }
  
  try {
    loading.value = true
    error.value = ''
    
    // 创建FormData
    const formData = new FormData()
    formData.append('file', file)
    
    // 上传到后端
    const token = localStorage.getItem('auth_token')
    const response = await fetch('/api/upload/avatar', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`
      },
      body: formData
    })
    
    const result = await response.json()
    
    if (result.code === 0) {
      form.value.avatarUrl = result.data
      console.log('头像上传成功:', result.data)
    } else {
      error.value = result.message || '头像上传失败'
    }
  } catch (e) {
    error.value = '头像上传失败: ' + e.message
  } finally {
    loading.value = false
  }
}

// 获取音色列表
const fetchVoiceList = async () => {
  try {
    const response = await fetch('/api/voice/list', {
      headers: {
        'Content-Type': 'application/json'
      }
    })
    const result = await response.json()
    if (result.code === 0) {
      voiceList.value = result.data || []
      console.log('获取音色列表成功:', voiceList.value)
    } else {
      console.error('获取音色列表失败:', result.message)
    }
  } catch (error) {
    console.error('获取音色列表错误:', error)
  }
}

// 选择音色
const selectVoice = (voiceType) => {
  selectedVoice.value = voiceType
  form.value.defaultVoiceType = voiceType
  showVoiceSelector.value = false
  console.log('选择音色:', voiceType)
}

// 试听音色
const previewVoice = async (voiceType) => {
  try {
    const token = localStorage.getItem('auth_token')
    const response = await fetch('/api/voice/preview', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ 
        voiceType: voiceType 
      })
    })
    const result = await response.json()
    if (result.code === 0) {
      // 创建音频对象并播放
      const audioBlob = new Blob([Uint8Array.from(atob(result.data), c => c.charCodeAt(0))], { type: 'audio/wav' })
      const audioUrl = URL.createObjectURL(audioBlob)
      const audio = new Audio(audioUrl)
      audio.play()
      
      // 播放完成后清理URL
      audio.onended = () => {
        URL.revokeObjectURL(audioUrl)
      }
    } else {
      console.error('音色试听失败:', result.message)
    }
  } catch (error) {
    console.error('音色试听失败:', error)
  }
}

// 获取音色显示名称
const getVoiceDisplayName = (voiceType) => {
  const voice = voiceList.value.find(v => v.voice_type === voiceType)
  return voice ? voice.voice_name || voice.voice_type : voiceType
}

const submitRole = async () => {
  if (!form.value.name.trim()) {
    error.value = '请输入角色名称'
    return
  }
  
  loading.value = true
  error.value = ''
  
  try {
    const token = localStorage.getItem('auth_token')
    if (!token) {
      router.push('/login')
      return
    }
    
    const roleData = {
      name: form.value.name,
      description: form.value.description,
      avatarUrl: form.value.avatarUrl || '',
      personality: form.value.personality,
      background: form.value.background,
      languageStyle: form.value.speakingStyle,
      promptTemplate: form.value.promptTemplate,
      openingLine: form.value.openingLine,
      tags: form.value.tags.split(',').map(tag => tag.trim()).filter(tag => tag).join(','),
      privacy: form.value.privacy,
      category: form.value.category,
      defaultVoiceType: form.value.defaultVoiceType || 'qiniu_zh_female_wwxkjx'
    }
    
    console.log('创建角色数据:', roleData)
    
    const res = await fetch('/api/roles', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(roleData)
    })
    
    const data = await res.json()
    
    if (data.code !== 0) {
      throw new Error(data.message || '创建角色失败')
    }
    
    // 创建成功，跳转到角色详情或我的角色页面
    router.push('/my-roles')
  } catch (e) {
    error.value = e.message || '创建角色失败，请重试'
  } finally {
    loading.value = false
  }
}

const goBack = () => {
  router.back()
}

// 组件挂载时获取音色列表
onMounted(() => {
  fetchVoiceList()
})
</script>

<style scoped>
.create-role-page {
  height: 100%;
  background: #f8fafc;
  padding: 40px 0;
  overflow-y: auto;
}

.container {
  width: 100%;
  padding: 0 32px;
}

.page-header {
  text-align: center;
  margin-bottom: 40px;
}

.page-title {
  font-size: 2.5rem;
  font-weight: 700;
  color: #1f2937;
  margin-bottom: 8px;
}

.page-subtitle {
  font-size: 1.125rem;
  color: #6b7280;
}

.form-container {
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 6px rgba(0,0,0,0.05);
  overflow: hidden;
  width: 100%;
}

.role-form {
  padding: 32px;
}

.form-section {
  margin-bottom: 32px;
}

.section-title {
  font-size: 1.25rem;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 20px;
  padding-bottom: 8px;
  border-bottom: 2px solid #e5e7eb;
}

.form-group {
  margin-bottom: 20px;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.form-label {
  display: block;
  font-weight: 500;
  color: #374151;
  margin-bottom: 6px;
}

.form-input,
.form-textarea,
.form-select {
  width: 100%;
  padding: 12px 16px;
  border: 2px solid #e5e7eb;
  border-radius: 8px;
  font-size: 16px;
  transition: all 0.2s;
  box-sizing: border-box;
}

.form-input:focus,
.form-textarea:focus,
.form-select:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.form-textarea {
  resize: vertical;
  min-height: 100px;
}

.form-checkbox {
  margin-right: 8px;
}

.avatar-upload {
  display: flex;
  align-items: center;
  gap: 20px;
}

.avatar-preview {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  overflow: hidden;
  background: #f3f4f6;
  border: 2px dashed #d1d5db;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s;
}

.avatar-preview:hover {
  border-color: #667eea;
  background: #f0f4ff;
}

.avatar-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  color: #6b7280;
}

.upload-icon {
  font-size: 24px;
}

.upload-text {
  font-size: 14px;
}

.avatar-input {
  display: none;
}

.voice-selector-container {
  position: relative;
}

.voice-selector {
  width: 100%;
  padding: 12px 16px;
  border: 2px solid #e5e7eb;
  border-radius: 8px;
  font-size: 14px;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  transition: all 0.2s;
}

.voice-selector:hover {
  border-color: #667eea;
}

.voice-selector:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.placeholder {
  color: #9ca3af;
}

.dropdown-arrow {
  color: #6b7280;
  transition: transform 0.2s;
}

.voice-selector:hover .dropdown-arrow {
  transform: rotate(180deg);
}

.voice-dropdown {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background: white;
  border: 2px solid #e5e7eb;
  border-radius: 8px;
  box-shadow: 0 4px 6px rgba(0,0,0,0.1);
  z-index: 1000;
  max-height: 200px;
  overflow-y: auto;
}

.voice-dropdown-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #e5e7eb;
  background: #f9fafb;
}

.voice-dropdown-header h4 {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
  color: #374151;
}

.close-btn {
  background: none;
  border: none;
  font-size: 18px;
  cursor: pointer;
  color: #6b7280;
  padding: 0;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  color: #374151;
}

.voice-list {
  max-height: 150px;
  overflow-y: auto;
}

.voice-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  cursor: pointer;
  transition: background-color 0.2s;
  border-bottom: 1px solid #f3f4f6;
}

.voice-item:hover {
  background: #f9fafb;
}

.voice-item.selected {
  background: #eff6ff;
  color: #1d4ed8;
}

.voice-item:last-child {
  border-bottom: none;
}

.voice-info {
  flex: 1;
}

.voice-name {
  display: block;
  font-weight: 500;
  font-size: 14px;
  margin-bottom: 2px;
}

.voice-description {
  display: block;
  font-size: 12px;
  color: #6b7280;
}

.voice-preview {
  margin-left: 12px;
}

.preview-btn {
  background: #667eea;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 4px 8px;
  font-size: 12px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.preview-btn:hover {
  background: #5a67d8;
}

.empty-voice-list {
  text-align: center;
  padding: 20px;
  color: #666;
}

.empty-voice-list p {
  margin: 0;
  font-size: 14px;
}

.error-message {
  background: #fef2f2;
  color: #dc2626;
  padding: 12px 16px;
  border-radius: 8px;
  border: 1px solid #fecaca;
  margin-bottom: 20px;
  font-size: 14px;
}

.form-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  margin-top: 32px;
  padding-top: 24px;
  border-top: 1px solid #e5e7eb;
}

.btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 12px 24px;
  border: none;
  border-radius: 8px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s;
  text-decoration: none;
}

.btn-primary {
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
}

.btn-primary:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.btn-primary:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

.btn-secondary {
  background: #f3f4f6;
  color: #374151;
  border: 1px solid #d1d5db;
}

.btn-secondary:hover {
  background: #e5e7eb;
}

.loading-spinner {
  width: 16px;
  height: 16px;
  border: 2px solid rgba(255,255,255,0.3);
  border-top: 2px solid white;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

@media (max-width: 768px) {
  .form-row {
    grid-template-columns: 1fr;
  }
  
  .avatar-upload {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .form-actions {
    flex-direction: column;
  }
}
</style>
